import logging
import datetime

from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, loader
from django.http import Http404

import facebook.djangofb as facebook
from esquinica.models import Event, Participant, Evite, Comment, \
                             EventForm

from esquinica import constants

from google.appengine.api import mail
from google.appengine.ext.webapp import template

from google.appengine.ext import db
from google.appengine.api import images
from google.appengine.ext.db import djangoforms
from google.appengine.ext.db import NotSavedError, Error

from google.appengine.api import users


# Create your views here.


def home(request):
    """
    redirects to the facebook home
    """
    
    user = users.get_current_user()
    
    if not user:
        logging.info("no user found")
    
    total_events = Event.all().count()
    
    event_list = Event.all().fetch(15)
    
    c = Context({                                           
         'list':event_list,    
    })
    t = loader.get_template('esquinica/loginList.html')
    return HttpResponse(t.render(c))
    
def createEvent(request):
    """
    Non-facebook method that
    creates an event based on the form object from django
    """
    logging.info("receiving the event")
    
    if request.method == 'POST':
        
        data = EventForm(data=request.POST)
        logging.info("processing the form")
        if data.is_valid():
            logging.info("data is valid")
            entity = data.save(commit=False)
            entity.put()
            logging.info("data saved")
        else:
            logging.info("data is invalid")
            c = Context({
                         'form':data,
                         }
                        )
            t = loader.get_template('esquinica/eventForm.html')
            return HttpResponse(t.render(c))
    
    
    else:
        form = EventForm()
        c = Context({                                           
         'form':form,    
        })
        t = loader.get_template('esquinica/eventForm.html')
        return HttpResponse(t.render(c))    
    
    # everythin else go to the list
    return HttpResponseRedirect("/pepe/home/")    

@facebook.require_login()
def fbDisplayEventForm(request):
    """
    Displays the form for the event
    """ 
    form = EventForm()
    c = Context({                                           
         'form':form,    
    })
    t = loader.get_template('esquinica/eventForm.html')
    return HttpResponse(t.render(c))           


def fbAddEventForm(request):
    """
    Add events to the database
    """
    data = EventForm(data=request.POST)
    logging.info("processing the event form")
    if data.is_valid():
        logging.info("data is valid")
        entity = data.save(commit=False)
        entity.author = request.facebook.uid
        entity.put()
        logging.info("event data added")
        str_url = r"/fb/esquinica/canvas/"
                        
        #return HttpResponseRedirect(str_url)
        c = Context({
               'event':entity,
             }
        )
        t = loader.get_template('esquinica/addParticipants.html')
        return HttpResponse(t.render(c)) 
        
    else:
        logging.info("data is invalid")
        c = Context({
               'form':data,
             }
        )
        t = loader.get_template('esquinica/eventForm.html')
        return HttpResponse(t.render(c))
    
        
@facebook.require_login()
def fbLogin(request):
    """
    login action to facebook
    """
    
    logging.info("just getting to login")
    
    # check to see if the user exists
    
    u = Participant.gql("WHERE ext_id = :1", request.facebook.uid ).get()
    
    if not u:
        # if does not exists well add the data
        
        str_query = "SELECT first_name, last_name, username, pic_small, birthday FROM user " \
                    "WHERE uid = %s" % (request.facebook.uid)
        
        logging.debug("SQL: %s" % str_query )
        user_info = request.facebook.fql.query(str_query)
        
        logging.info("after query")
        
        u = Participant(
                            first_name = user_info[0]['first_name'],
                            last_name = user_info[0]['last_name'],
                            nickname = user_info[0]['username'],
                            pic_src =  user_info[0]['pic_small'],
                            bday = user_info[0]['birthday'],
                            ext_id = request.facebook.uid,
                            dt_last_updated = datetime.datetime.now(),
                            state = constants.STATUS_ACTIVE,
                            )
        logging.info("before saving")
#            u.dt_last_updated = datetime.datetime.now()
        try:
            u.put()
        except NotSavedError, (strerr):
            logging.error("Not saved: %s" % strerr )
            
        logging.info("user saved")
    
    c = Context({                                           
        'uid':request.facebook.uid,    
    })
    t = loader.get_template('esquinica/canvas.html')
    return HttpResponse(t.render(c))
    
@facebook.require_login()
def fbPostLogin(request):
    """
    Called after the user logs in for the first time. It does not require a 
    redirect. All info send as a post.
    """
    
    logging.info("just getting to the first login")
    str_uid = None
    
    try:
        str_uid = request.POST['fb_sig_user']
        #user session key
        str_usr_session_key = request.POST['fb_sig_session_key']
        
        logging.info("detection went ok")
        
    except KeyError, (strErr):
        logging.error("Error en post login: %s" %  strErr )
        return
    
    #logging.info("user: %s" % int_uid )
    
    result_set = Participant.gql("WHERE ext_id = :1", str_uid).get()
    
    if not result_set:
        logging.info("first time the user logins")
        p = Participant(ext_id=str_uid, 
                     state= constants.STATUS_TRANSIENT,
                     email=str_uid)
    
        p.put()
    else:
        result_set.state = constants.STATUS_ACTIVE
        result_set.put()    
    
    
    
        
def fbRemove(request):
    """
    gets called whenever the user signs out
    """
    str_user = None
    
    # participant
    p = None    
    try:
        str_user = request.POST['fb_sig_user']
        p = Participant.gql("WHERE ext_id = :1", str_user).get()
    except KeyError, (strerr):
        logging.error("error removing: %s" % strerr)
        
    if str_user:
        p.state = constants.STATUS_INACTIVE
        p.dt_last_updated = datetime.datetime.now()
        p.put()
        logging.info("user removed")

@facebook.require_login()
def fbDisplayAddParticipant(request):
    """
    Displays the form to add participants of the event
    """
    
    # TODO: anhadir mensaje
    c = Context({                                           
        'uid':request.facebook.uid,    
    })
    t = loader.get_template('esquinica/addParticipants.html')
    return HttpResponse(t.render(c))

@facebook.require_login()
def fbAddParticipant(request):
    """
    Process the form and receives the list of friends through the friend selectors
    """
    
    logging.info("adding friends selector")
    
    list_of_friends = request.POST.getlist('ids[]')
    
    logging.info("total friends added: %d" % len(list_of_friends) )
    
    
    
    #TODO: anhadir el procesamiento de ids[]
    c = Context({                                           
        'uid':request.facebook.uid,    
    })
    t = loader.get_template('esquinica/canvas.html')
    return HttpResponse(t.render(c))    
    
        
def fbOther(request):
    """
    Other page not found during the facebook integration
    """
    c = Context({                                           
        'uid':'0',    
    })
    t = loader.get_template('esquinica/other.html')
    return HttpResponse(t.render(c))        